### Input params check
cmake_minimum_required(VERSION 3.0)

string(COMPARE EQUAL "@configure_command@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "configure_command is empty")
endif()

string(COMPARE EQUAL "@qt_component@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "qt_component is empty")
endif()

string(COMPARE EQUAL "@hunter_self@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "hunter_self is empty")
endif()

string(COMPARE EQUAL "@is_release_debug@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "is_release_debug is empty")
endif()

string(COMPARE EQUAL "@is_release@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "is_release is empty")
endif()

string(COMPARE EQUAL "@is_debug@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "is_debug is empty")
endif()

string(COMPARE EQUAL "@HUNTER_Qt_VERSION@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "HUNTER_Qt_VERSION is empty")
endif()

string(COMPARE EQUAL "@global_install_dir@" "" is_empty)
if(is_empty)
  message(FATAL_ERROR "global_install_dir is empty")
endif()

### -- end

include("@hunter_self@/scripts/clear-all.cmake")

if("@HUNTER_QT_OS_IS_LINUX@")
  set(x "@global_install_dir@/share/pkgconfig")
  set(y "@global_install_dir@/lib/pkgconfig")
  set(ENV{PKG_CONFIG_PATH} "${x}:${y}")

  set(ENV{LD_LIBRARY_PATH} "@global_install_dir@/lib")
endif()

list(APPEND CMAKE_MODULE_PATH "@hunter_self@/cmake/modules")

include(hunter_generate_qt_info)
include(hunter_user_error)

hunter_generate_qt_info(
    "@qt_component@"
    components_toskip
    depends_on
    nobuild_list
    "@HUNTER_Qt_VERSION@"
    "@ANDROID@"
    "@WIN32@"
)

message("\nBuilding Qt component:\n  @qt_component@\n")

message("Dependent components:")
foreach(x ${depends_on})
  message("  ${x}")
endforeach()
message("\n")

message("Components to skip:")
set(components_opts)
foreach(x ${components_toskip})
  message("  ${x}")
  list(APPEND components_opts "-skip" "${x}")
endforeach()
message("\n")

set(configure_command "@configure_command@" ${components_opts})

if("@IOS@")
  set(dev_archs_oneline "@IPHONEOS_ARCHS@")
  set(sim_archs_oneline "@IPHONESIMULATOR_ARCHS@")
  set(deployment_target "@CMAKE_XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET@")

  string(REPLACE ";" " " dev_archs_oneline "${dev_archs_oneline}")
  string(REPLACE ";" " " sim_archs_oneline "${sim_archs_oneline}")

  set(
      conf_path
      "${CMAKE_CURRENT_LIST_DIR}/qtbase/mkspecs/macx-ios-clang/qmake.conf"
  )

  string(COMPARE EQUAL "${deployment_target}" "" is_empty)
  if(is_empty)
    message(
        FATAL_ERROR
        "CMAKE_XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET is empty (should be set in iOS toolchain)"
    )
  endif()

  file(STRINGS "${conf_path}" lines)

  set(output_content "")
  foreach(line ${lines})
    set(output ${line})
    string(
        REGEX
        REPLACE
        "^QMAKE_IOS_DEVICE_ARCHS[ ]*=.*$"
        "QMAKE_IOS_DEVICE_ARCHS = ${dev_archs_oneline}"
        output
        "${output}"
    )
    string(
        REGEX
        REPLACE
        "^QMAKE_IOS_SIMULATOR_ARCHS[ ]*=.*$"
        "QMAKE_IOS_SIMULATOR_ARCHS = ${sim_archs_oneline}"
        output
        "${output}"
    )
    string(
        REGEX
        REPLACE
        "^QMAKE_IOS_DEPLOYMENT_TARGET[ ]*=.*$"
        "QMAKE_IOS_DEPLOYMENT_TARGET = ${deployment_target}"
        output
        "${output}"
    )
    set(output_content "${output_content}\n${output}")
  endforeach()

  string(COMPARE EQUAL "@CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM@" "" is_empty)
  if(NOT is_empty)
    # https://bugreports.qt.io/browse/QTCREATORBUG-16968?focusedCommentId=333849&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-333849
    set(team "HUNTER_DEVELOPMENT_TEAM.value = @CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM@")
    set(team "${team}\nHUNTER_DEVELOPMENT_TEAM.name = DEVELOPMENT_TEAM")
    set(team "${team}\nQMAKE_MAC_XCODE_SETTINGS += HUNTER_DEVELOPMENT_TEAM")

    set(output_content "${output_content}\n${team}")
  endif()

  file(WRITE "${conf_path}" "${output_content}\n")
endif()

if("@IOS@" AND NOT "@is_release_debug@")
  # Workaround for https://bugreports.qt.io/browse/QTBUG-48348

  if("@is_release@")
    set(pattern_to_remove ".*_populate_.*_target_properties\\(DEBUG .*")
  elseif("@is_debug@")
    set(pattern_to_remove ".*_populate_.*_target_properties\\(RELEASE .*")
  else()
    message(FATAL_ERROR "Not Release and not Debug")
  endif()

  set(
      template_path
      "${CMAKE_CURRENT_LIST_DIR}/qtbase/mkspecs/features/data/cmake/Qt5BasicConfig.cmake.in"
  )

  file(STRINGS "${template_path}" lines)

  set(output_content "")
  foreach(line ${lines})
    set(output ${line})
    string(REGEX REPLACE "${pattern_to_remove}" "" output "${output}")
    set(output_content "${output_content}\n${output}")
  endforeach()

  file(WRITE "${template_path}" "${output_content}\n")
endif()

if("@HUNTER_PATCH_QT_MACX_CLANG@")
  # inherit variables from parent
  set(OSX_SDK_VERSION "@OSX_SDK_VERSION@")
  set(CMAKE_OSX_SYSROOT "@CMAKE_OSX_SYSROOT@")

  string(COMPARE EQUAL "${OSX_SDK_VERSION}" "" sdk_is_empty)
  string(COMPARE EQUAL "${CMAKE_OSX_SYSROOT}" "" osx_sysroot_is_empty)

  if(sdk_is_empty AND osx_sysroot_is_empty)
    hunter_user_error(
        "Can't determine SDK. Please set OSX_SDK_VERSION or CMAKE_OSX_SYSROOT in toolchain."
    )
  endif()

  if(sdk_is_empty)
    # Try to determine SDK version from CMAKE_OSX_SYSROOT
    string(REGEX REPLACE ".*/MacOSX([0-9]*\\.[0-9]*)\\.sdk$" "\\1" OSX_SDK_VERSION "${CMAKE_OSX_SYSROOT}")

    string(COMPARE EQUAL "${OSX_SDK_VERSION}" "${CMAKE_OSX_SYSROOT}" replace_failed)
    if(replace_failed)
      hunter_user_error(
          "Can't determine SDK version from string: ${CMAKE_OSX_SYSROOT}"
      )
    endif()
  endif()

  string(COMPARE EQUAL "${CMAKE_OSX_DEPLOYMENT_TARGET}" "" is_empty)
  if(is_empty)
    set(CMAKE_OSX_DEPLOYMENT_TARGET "${OSX_SDK_VERSION}")
  endif()

  ### Set deployment target {
  set(
      conf_path
      "${CMAKE_CURRENT_LIST_DIR}/qtbase/mkspecs/macx-clang/qmake.conf"
  )

  file(STRINGS "${conf_path}" lines)

  set(output_content "")
  foreach(line ${lines})
    set(output ${line})
    string(
        REGEX
        REPLACE
        "^QMAKE_MACOSX_DEPLOYMENT_TARGET[ ]*=.*$"
        "QMAKE_MACOSX_DEPLOYMENT_TARGET = ${CMAKE_OSX_DEPLOYMENT_TARGET}"
        output
        "${output}"
    )
    set(output_content "${output_content}\n${output}")
  endforeach()

  file(WRITE "${conf_path}" "${output_content}\n")
  ### }

  ### Set SDK version {
  set(
      conf_path
      "${CMAKE_CURRENT_LIST_DIR}/qtbase/mkspecs/common/macx.conf"
  )

  file(STRINGS "${conf_path}" lines)

  set(output_content "")
  foreach(line ${lines})
    set(output ${line})
    string(
        REGEX
        REPLACE
        "^QMAKE_MAC_SDK[ ]*=.*$"
        "QMAKE_MAC_SDK = macosx${OSX_SDK_VERSION}"
        output
        "${output}"
    )
    set(output_content "${output_content}\n${output}")
  endforeach()

  file(WRITE "${conf_path}" "${output_content}\n")
  ### }
endif()

if("@HUNTER_QT_OS_IS_LINUX@")
  # inherit variables from parent
  set(CMAKE_CXX_COMPILER "@CMAKE_CXX_COMPILER@")
  set(CMAKE_C_COMPILER "@CMAKE_C_COMPILER@")

  set(
      conf_path
      "${CMAKE_CURRENT_LIST_DIR}/qtbase/mkspecs/common/g++-base.conf"
  )

  file(STRINGS "${conf_path}" lines)

  set(output_content "")
  foreach(line ${lines})
    set(output ${line})
    string(
        REGEX
        REPLACE
        "^QMAKE_COMPILER[ ]*=.*$"
        "QMAKE_COMPILER = ${CMAKE_C_COMPILER}"
        output
        "${output}"
    )
    string(
        REGEX
        REPLACE
        "^QMAKE_CC[ ]*=.*$"
        "QMAKE_CC = ${CMAKE_C_COMPILER}"
        output
        "${output}"
    )
    string(
        REGEX
        REPLACE
        "^QMAKE_CXX[ ]*=.*$"
        "QMAKE_CXX = ${CMAKE_CXX_COMPILER}"
        output
        "${output}"
    )
    set(output_content "${output_content}\n${output}")
  endforeach()

  if("@HUNTER_Qt_VERSION@" VERSION_LESS "5.12")
    file(WRITE "${conf_path}" "${output_content}\n")
    message("Set g++-base.conf content to:\n")
    message("${output_content}")
  else()
    # FIXME
  endif()
endif()

function(calculate_list listname)
  message("Calculating list of files...")
  file(
      GLOB_RECURSE
      result
      RELATIVE
      "${CMAKE_CURRENT_LIST_DIR}"
      "${CMAKE_CURRENT_LIST_DIR}/.qmake.super"
      "${CMAKE_CURRENT_LIST_DIR}/Makefile"
      "${CMAKE_CURRENT_LIST_DIR}/*/*.pri"
      "${CMAKE_CURRENT_LIST_DIR}/*/*.prl"
      "${CMAKE_CURRENT_LIST_DIR}/*/.qmake.cache"
      "${CMAKE_CURRENT_LIST_DIR}/*/Makefile*"
      "${CMAKE_CURRENT_LIST_DIR}/*/config.status"
      "${CMAKE_CURRENT_LIST_DIR}/*/config.summary"
      "${CMAKE_CURRENT_LIST_DIR}/*/qt.conf"
  )
  set("${listname}" "${result}" PARENT_SCOPE)
  message("Done")
endfunction()

string(COMPARE EQUAL "@qt_component@" "qtbase" is_qtbase)
set(original_list_path "${CMAKE_CURRENT_LIST_DIR}/original-list.cmake")
set(original_list_temp "${CMAKE_CURRENT_LIST_DIR}/original-list.temp")
if(EXISTS "${original_list_path}")
  # Not the first component that is built in this directory
  # Do clean-up before configure
  set(original_list "")
  include(${original_list_path})
  string(COMPARE EQUAL "${original_list}" "" is_empty)
  if(is_empty)
    message(FATAL_ERROR "Can't load list from file: ${original_list}")
  endif()

  calculate_list(list_to_remove)
  list(REMOVE_ITEM list_to_remove ${original_list})
  message("Clean-up...")
  foreach(x ${list_to_remove})
    message("removing: ${x}")
    file(REMOVE ${x})
  endforeach()
else()
  # First component that is building in this directory
  # Save all original file list
  calculate_list(original_list)
  file(WRITE "${original_list_temp}" "set(original_list \"\")\n")
  foreach(x ${original_list})
    file(APPEND "${original_list_temp}" "list(APPEND original_list \"${x}\")\n")
  endforeach()
  # atomic rename
  file(RENAME "${original_list_temp}" "${original_list_path}")
endif()

message("Qt configure command: ${configure_command}")

execute_process(COMMAND ${configure_command} RESULT_VARIABLE result)

if(NOT result EQUAL 0)
  message(FATAL_ERROR "Qt configure failed: ${result}")
endif()
